import React, { useState, useEffect, useRef, useImperativeHandle } from 'react';
import { Row, Col, Button, Select, message } from 'antd';
import OtherBtn from '../otherBtn';
import RulesetPannel from './pannel';
import { randomKey } from 'src/utils/utils';
import { cloneDeep } from 'lodash';
import Modal from 'src/components/Modal';
import Question from 'src/components/Question';
import { EXCUTE_MODE } from 'src/utils/constant';
import RuleConfig from './ruleConfig';
import { compare } from 'src/utils/compare';

const initValue = {
  name: '',
  code: '',
  id: '',
  enabled: true,
  priority: 9999,
  condition: {
    conditions: [],
    junction_type: 'or',
    id: randomKey(),
  },
  condition_actions: [
    {
      action_type: 'condition_true',
      actions: [],
    },
    {
      action_type: 'condition_false',
      actions: [],
    },
  ],
};

export default function RuleSet(props) {
  const { value, execute_mode = '', compareData, disabled = false, projectCode } = props;
  const [excuteMode, setExcuteMode] = useState('');
  const [rules, setRules] = useState([]);
  const [openStatus, setOpenStatus] = useState(false);
  const _ruleConfig = useRef(null);
  useImperativeHandle(props.createRefR, () => ({
    // 暴露方法给父组件,收集值，验证应该放到这里，后面再做
    getValue: (values) => {
      return { execute_mode: excuteMode, express_rules: rules };
    },
  }));

  useEffect(() => {
    setExcuteMode(execute_mode);
  }, [execute_mode]);

  useEffect(() => {
    if (value && value.length > 0) {
      const _value = initData(value);
      setRules(cloneDeep(_value));
    }
  }, [value]);

  function initData(data) {
    const newData = data.map((item) => {
      item.id = item.id ? item.id : randomKey();
      return item;
    });
    return newData;
  }

  // 删除
  function del(it) {
    // console.log(it, rules);
    const key = randomKey();
    Modal.open({
      title: '',
      width: '360px',
      isConfirm: true,
      content: <p>确定要删除本条规则么?</p>,
      isOkBtn: true,
      isCancelBtn: true,
      key: key,
      ok: () => {
        const newRules = rules.filter((rule) => rule.id !== it.id);
        setRules(cloneDeep(newRules));
        Modal.close(key);
      },
      cancel: () => {
        Modal.close(key);
      },
    });
  }

  // 复制
  function copy(it, index) {
    const _id = randomKey();
    const key = randomKey();

    let item = {
      ...it,
      id: _id,
      code: '',
      name: '',
    };
    if (item.condition_actions) item.condition_actions = item.condition_actions.map((i) => ({ ...i, id: randomKey() }));
    if (item.conditions) item.conditions = item.conditions.map((i) => ({ ...i, id: randomKey() }));

    Modal.open({
      title: '复制并新增规则',
      width: '1200px',
      content: (
        <RuleConfig
          variable={props.variable}
          value={item}
          operator={props.operator}
          actions={props.actions}
          ruleRef={_ruleConfig}
          riskTypes={props.riskTypes}
          otherRules={rules}
        />
      ),
      isOkBtn: true,
      isCancelBtn: true,
      key: key,
      ok: () => {
        _ruleConfig.current.getValue((value, error) => {
          console.log(value, error);
          if (!error) {
            rules.splice(index + 1, 0, value);
            setRules(cloneDeep(rules));
            Modal.close(key);
          }
        });
      },
      cancel: () => {
        Modal.close(key);
      },
    });
  }

  // 编辑
  function edit(it, index) {
    const key = randomKey();
    Modal.open({
      title: '编辑',
      width: '1200px',
      content: (
        <RuleConfig
          variable={props.variable}
          value={it}
          operator={props.operator}
          actions={props.actions}
          ruleRef={_ruleConfig}
          riskTypes={props.riskTypes}
          otherRules={rules.filter((item) => item.id !== it.id)}
        />
      ),
      isOkBtn: true,
      isCancelBtn: true,
      key: key,
      ok: () => {
        _ruleConfig.current.getValue((value, error) => {
          if (!error) {
            rules[index] = value;
            setRules(cloneDeep(rules));
            Modal.close(key);
          }
        });
      },
      cancel: () => {
        Modal.close(key);
      },
    });
  }

  //添加规则
  function addRule() {
    if (!projectCode) return message.warning('请选择所属项目！');
    const value = {
      ...cloneDeep(initValue),
      id: randomKey(),
    };
    const key = randomKey();
    Modal.open({
      title: '添加规则',
      width: '1200px',
      content: (
        <RuleConfig
          variable={props.variable}
          value={value}
          operator={props.operator}
          actions={props.actions}
          ruleRef={_ruleConfig}
          riskTypes={props.riskTypes}
          otherRules={rules}
        />
      ),
      isOkBtn: true,
      isCancelBtn: true,
      key: key,
      ok: () => {
        _ruleConfig.current.getValue((value, error) => {
          if (!error) {
            rules.push(value);
            setRules(cloneDeep(rules));
            Modal.close(key);
          }
        });
      },
      cancel: () => {
        Modal.close(key);
      },
    });
  }

  // 折叠/打开规则
  function toggleRules() {
    setOpenStatus(!openStatus);
    document.querySelectorAll('.rule-pannel-collapse').forEach((item) => {
      if (!openStatus) {
        item.className = 'rule-pannel-collapse open';
        // setTimeout(() => {
        //   this.props.updateRenderBody && this.props.updateRenderBody(item.getAttribute('id'));
        // }, 100);
      } else {
        item.className = 'rule-pannel-collapse';
      }
    });
  }

  // 排序
  function sortRules() {
    const newRules = rules.map((it, i) => {
      it.oldIndex = i;
      return it;
    });

    newRules.sort((a, b) => {
      return a.priority - b.priority || a.oldIndex - b.oldIndex;
    });
    // console.log(newRules);
    setRules(cloneDeep(newRules));
  }

  return (
    <div>
      {/* <ExecuteMode {...props} value={value.execute_mode} /> */}
      <Row type='flex' gutter={10} align='middle' style={{ marginBottom: '20px' }}>
        <Col span={3}>执行模式:</Col>
        <Col span={8}>
          <Select
            value={excuteMode}
            disabled={disabled}
            onChange={(value) => setExcuteMode(value)}
            style={compare({ ...props, value: { execute_mode: props.execute_mode } }, 'execute_mode')}
          >
            {EXCUTE_MODE.map((it, index) => {
              return (
                <Select.Option value={it.value} key={index}>
                  {it.label}
                </Select.Option>
              );
            })}
          </Select>
        </Col>
        <Col>
          <Question
            title={
              <div>
                <p>1.互斥执行：从上到下执行，无论有没有退出动作，一旦规则命中，则不再向下执行；</p>
                <p>2.普通执行：从上到下执行，除非遇到退出动作，否则会顺序执行所有规则；</p>
              </div>
            }
          />
        </Col>
      </Row>
      {!disabled ? (
        <Row type='flex' justify='space-between' style={{ marginTop: '20px' }}>
          <Col>
            <Row type='flex' justify='start' gutter={10}>
              <Col>
                <Button type='primary' onClick={() => addRule()}>
                  添加规则
                </Button>
              </Col>
              {/* <OtherBtn {...props} onComplete={props.reloadVariable} /> */}
            </Row>
          </Col>
          <Col>
            <Row type='flex' justify='end' gutter={10} style={{ marginBottom: '10px' }}>
              <Col>
                <Button onClick={() => sortRules()}>规则排序</Button>
              </Col>
              <Col>
                <Button onClick={() => toggleRules()}>{openStatus ? '折叠规则' : '展开规则'}</Button>
              </Col>
            </Row>
          </Col>
        </Row>
      ) : (
        <Row type='flex' justify='end' style={{ margin: '20px 0 10px 0' }}>
          <Col>
            <Button onClick={() => toggleRules()}>{openStatus ? '折叠规则' : '展开规则'}</Button>
          </Col>
        </Row>
      )}

      {rules.map((it, index) => {
        return (
          <RulesetPannel
            {...props}
            actions={props.actions}
            variable={props.variable}
            value={it}
            cid={it.id}
            operator={props.operator}
            renderBody={openStatus}
            copy={() => copy(it, index)}
            del={() => del(it)}
            edit={() => edit(it, index)}
            key={it.id}
            disabled={props.disabled}
            compareData={compareData.express_rules && compareData.express_rules[index]}
          />
        );
      })}
    </div>
  );
}
